Iconify JSON tools
This library is used to manipulate JSON icon collections.
The library is available for PHP and Node.js, code in both versions is almost identical.
Installation
To install the library run this command:
npm install @iconify/json-tools --save
There are two classes in this package: Collection
and SVG
Collection class
Collection class represents an icon set.
To include it use this code:
const Collection = require('@iconify/json-tools').Collection;
What can Collection class do?
- Read and write JSON collections.
- Add, remove, list icons in an icon set.
- Retrieve icon data.
- Create icon bundles for Iconify icon sets.
Initializing class instance
There are two ways to create an instance: with icon set prefix and without icon set prefix.
You can skip icon set prefix in the constructor if you are going to load data from a JSON file because JSON files contain icon set prefix.
let collection = new Collection();
let collectionWithPrefix = new Collection('custom-icons');
Loading JSON data
There are several functions to load an icon set from JSON file:
loadFromFile()
- loads collection synchronously.loadFromFileAsync()
- loads collection asynchronously (not available in PHP version).loadJSON()
- loads JSON data from string or object.loadIconifyCollection()
- loads Iconify collection from @iconify/json
repository.
loadFromFile()
This function loads an icon set from a JSON file.
Function parameters:
file
- file to load data from.defaultPrefix
- optional default prefix in case if JSON file does not have it.
Returns:
- boolean - true on success, false on failure
let collection = new Collection();
if (!collection.loadFromFile('json/custom-icons.json')) {
console.error('Failed to load custom-icons.json');
}
loadFromFileAsync()
This function is similar to loadFromFile()
, but it returns Promise
and loads file asynchronously.
This function is not available in PHP version of this library.
let collection = new Collection();
collection
.loadFromFileAsync('json/custom-icons.json')
.then((collection) => {
console.log('Loaded custom-icons.json');
})
.catch((err) => {
console.error('Failed to load custom-icons.json');
});
loadJSON()
This function loads an icon set from a string or an object.
Function parameters:
data
- JSON string or object.prefix
- optional prefix if JSON file doesn't include one.
Returns:
- boolean - true on success, false on failure
let collection = new Collection();
if (!collection.loadJSON(data)) {
console.error('Failed to load JSON data');
}
let collection = new Collection();
if (!collection.loadJSON(data, 'custom-icons')) {
console.error('Failed to load JSON data');
}
loadIconifyCollection()
This function loads Iconify icon set from @iconify/json repository.
Function parameters:
name
- the name of the icon set.dir
- optional root directory of Iconify icon set. Use this option if you want to load Iconify icon set from a custom directory instead of the @iconify/json
repository.
Returns:
- boolean - true on success, false on failure
let collection = new Collection();
if (!collection.loadIconifyCollection('mdi')) {
console.error('Failed to load Material Design Icons');
}
Getting icon data
There are several functions that retrieve icon data from an icon set:
getIconData()
- returns full data for one icon. It can be used to generate SVG (see SVG class documentation below).getIcons()
- returns JSON data for icons, which can be used to import to another JSON collection or can be added to Iconify using Iconify.addCollection()
.scriptify()
- returns JavaScript bundle file that can be used to load icons in browser with Iconify.
getIconData()
This function returns JSON data for one icon. It returns full data, including optional fields, so the result can be used to generate SVG.
Function parameters:
Returns:
let data = collection.getIconData('arrow-left');
let svg = new SVG(data);
containerNode.innerHTML = svg.getSVG({});
getIcons()
This function returns JSON data for selected icons. If used without parameters, it returns JSON data for an entire icon set.
Function parameters:
icons
- icon names array.
let data = collection.getIcons(['arrow-left', 'arrow-right', 'home']);
fs.writeFileSync('bundle.json', JSON.stringify(data), 'utf8');
This function can also be used to copy collection:
let data = collection.getIcons();
let newCollection = new Collection();
newCollection.loadJSON(data);
Using collection.getIcons()
without parameters is the same as accessing collection.items
object.
Warning: if you use getIcons()
without parameters, editing result object will affect data stored in collection instance.
getIcons()
does not make a copy of the object if you request an entire collection. This does not apply to PHP version of this library.
scriptify()
This is similar to getIcons()
, but it generates JavaScript file instead of JSON data and parameters are passed as one object.
Function parameters:
options
- options object.
Returns:
- string - JavaScript code you can bundle with your scripts.
Options object properties:
icons
- an array of icons to retrieve. If not set or null, all icons will be retrieved.optimize
- boolean. If set to true, JSON data will be optimized to make output smaller.pretty
- boolean. If set to true, JSON data will include white spaces that make output easy to read.callback
- string. JavaScript callback to wrap JSON data in. The default value is Iconify.addCollection
.
Code to create a bundle with selected icons from one collection (repeat same code for different collections to make bundle of all icons used on website):
let collection = new Collection();
if (!collection.loadIconifyCollection('mdi')) {
throw new Error('Cannot load Material Design Icons');
}
let code = collection.scriptify({
icons: ['account', 'account-alert', 'home', 'book-open'],
pretty: false,
optimize: true,
});
fs.writeFileSync('bundle-mdi.js', code, 'utf8');
Adding/removing icons
addIcon()
This function adds a new icon to the icon set.
Function parameters:
name
- icon name.data
- icon data.
Returns:
- boolean - true on success, false on failure. Failure is possible if an icon is missing 'body' property of if the icon set has no prefix
let collection = new Collection('custom-icons');
collection.addIcon('arrow', {
body: '<path d="" />',
width: 24,
height: 24,
});
addAlias()
This function adds an alias for an existing icon.
Function parameters:
name
- alias name.parent
- parent icon name.data
- optional data that should override parent icon's data (such as rotation or flip).
Returns:
- boolean - true on success, false on failure. Failure is possible if the parent icon is missing.
let collection = new Collection('custom-icons');
collection.addIcon('arrow-left', {
body: '<path d="" />',
width: 24,
height: 24,
});
collection.addAlias('arrow-right', 'arrow-left', {
hFlip: true,
});
collection.addAlias('arrow-right-alias', 'arrow-right');
setDefaultIconValue()
Set default value for all icons.
Function parameters:
key
- attribute name.value
- default value.
collection.setDefaultIconValue('height', 24);
removeIcon()
Removes an icon or an alias from the icon set.
Function parameters:
name
- icon name.checkAliases
- if true, the icon set will be checked for aliases that use removed icon as parent icon and those aliases will be removed too. Set to false if you know for sure there are no aliases referencing this icon, otherwise set to true.
let collection = new Collection();
collection.loadIconifyCollection('fa-solid');
collection.removeIcon('home');
iconExists()
Checks if an icon or an alias exists.
Function parameters:
Returns:
if (!collection.iconExists('home')) {
console.error('Missing "home" icon!');
}
listIcons()
Lists all icons in an icon set.
Function parameters:
includeAliases
- set to true to include aliases in the result.
Returns:
let collection = new Collection();
collection.loadIconifyCollection('vaadin');
console.log(
'Available icons in vaadin collection:',
collection.listIcons(true)
);
Other functions
items
This is a property, not a function. You can use it to have access to raw JSON data. Value is the same as using getIcons()
without parameters.
prefix()
Returns the icon set prefix, false
if the icon set has no prefix.
Returns:
- string|boolean - Prefix,
false
on error.
let prefix = collection.prefix();
findIconifyCollection()
This function locates Iconify icon set from @iconify/json repository.
Function parameters:
name
- Prefix of the icon set.dir
- Optional root directory where Iconify icon sets are stored. Use this option if you want to load Iconify icon set from a custom directory instead of the @iconify/json
repository.
Returns:
- string - location of the file.
console.log(
'fa-solid.json can be found at',
Colleciton.findIconifyCollection('fa-solid')
);
optimize()
Optimize is a static function that optimizes JSON data. It modifies the object passed in the first parameter.
Function parameters:
data
- JSON object to optimize.props
- an optional array of properties to optimize. If not set, default properties list will be used.
let data = JSON.parse(JSON.stringify(collection.getIcons()));
Collection.optimize(data);
deOptimize()
Opposite of the previous function. It converts optimized JSON data into full JSON data, making it easy to retrieve data for each icon.
Function parameters:
data
- JSON object to de-optimize.
let data = JSON.parse(fs.readFileSync('ant-design.json', 'utf8'));
Collection.deOptimize(data);
SVG class
The SVG
class generates code for the icon.
To include it use this code:
const SVG = require('@iconify/json-tools').SVG;
Usually it should be used with the Collection
class, so include should look like this:
const { SVG, Collection } = require('@iconify/json-tools');
Initializing class instance
let svg = new SVG(data);
Getting SVG icon
The SVG
class has one function: getSVG()
. It returns SVG as a string.
const { SVG, Collection } = require('@iconify/json-tools');
let collection = new Collection();
collection.loadIconifyCollection('mdi');
let svg = new SVG(collection.getIconData('home'));
console.log(svg.getSVG({}));
getSVG()
has one parameter: custom properties object. Possible object attributes:
inline
- if true or "true" or "1" (string or boolean), code will include vertical-align
style, making it behave like a glyph. See inline vs block article.width
, height
- dimensions of icon. If only one attribute is set, another attribute will be set using icon's width/height ratio. Value can be string (such as "1em", "24px" or number). If value is "auto", icon's original dimensions will be used. If both width and height are not set, height defaults to "1em".hFlip
, vFlip
- if true or "true" or "1" (string or boolean), icon will be flipped horizontally and/or vertically.flip
- alternative to "hFlip" and "vFlip", string. Value can be "horizontal", "vertical" or "horizontal,vertical"rotate
- rotation. Value can be in degrees "90deg" (only 90, 180 and 270 rotations are available), percentages "25%" (25%, 50% and 75% are aliases of 90deg, 180deg and 270deg) or number 1-3 (1 - 90deg, 2 - 180deg, 3 - 270deg).align
- alignment. This is useful if you have custom width and height set. Unlike other images, SVG keep aspect ratio (unless stated otherwise) when scaled. Value is comma or space separated string with possible strings (example: "left,top,crop"):
left
, right
, center
- horizontal alignmenttop
, middle
, bottom
- vertical alignmentcrop
- crop parts that go outside of boundariesmeet
- scale icon down to fit entire icon (opposite of crop)
color
- custom color string to replace currentColor. This is useful when using icon as background image because background image cannot use currentColorbox
- if true or "true" or "1" (string or boolean), icon will include extra rectangle matching its view box. This is useful to export icon to editor making icon easier to scale or place into its position in sketch because often editors ignore viewBox.
svg.getSVG({
height: '24px',
});
svg.getSVG({
height: '24px',
width: '24px',
align: 'center,middle,meet',
color: '#ff8000',
rotate: '90deg',
flip: 'horizontal',
box: true,
});
svg.getSVG({
height: 'auto',
});
License
The library is released with MIT license.
© 2018 - 2020 Vjacheslav Trushkin